/*
 * 页面缓存拦截
 */
import { Router, RouteLocationNormalized } from 'vue-router'
import { useKeepAliveStoreOutside } from '@/store/modules/keepAlive'
import { ENABLE_KEEP_ALIVE } from '@/settings'

const keepAliveStore = useKeepAliveStoreOutside()

export default function createKeepaliveGuard (router:Router) {
  router.beforeEach((to, from, next) => {
    addKeepAlive(to)
    addvisited(to, from)
    next()
  })

  router.afterEach((to, from) => {
    delvisited(to, from)
  })
}

// 添加缓存
function addKeepAlive (to:RouteLocationNormalized) {
  const keepAlive = !!to.meta?.keepAlive
  const ignoreKeepAlive = !!to.meta?.ignoreKeepAlive
  const name = to.name || 'no-name'

  if ((ENABLE_KEEP_ALIVE && !ignoreKeepAlive) || keepAlive) {
    keepAliveStore.addCachePage(name as string)
  }
}

// 添加缓存记录
function addvisited (to:RouteLocationNormalized, from:RouteLocationNormalized) {
  const visited = from.params._visited_ || false
  const fName = from.name || 'no-name'
  const tName = to.name || 'no-name'
  if (visited) {
    keepAliveStore.addCachePage(fName as string)
    keepAliveStore.addVisited(fName as string)
    keepAliveStore.addVisited(tName as string)
  }
}

// 删除缓存记录
function delvisited (to:RouteLocationNormalized, from:RouteLocationNormalized) {
  const keepAlive = !!to.meta?.keepAlive
  const isVisited = from.params._visited_ || false
  const visited = keepAliveStore.visitedList
  const last = visited[visited.length - 1]
  const lastOne = visited[visited.length - 2]
  const tName = to.name || 'no-name'
  const fName = from.name || 'no-name'

  if (tName === lastOne && fName === last) {
    keepAliveStore.delVisited(tName)
    keepAliveStore.delVisited(fName)
    if (!keepAlive && !ENABLE_KEEP_ALIVE) {
      setTimeout(() => {
        // 延迟清除缓存
        keepAliveStore.delCachePage(tName)
      }, 500)
    }
  } else if (!isVisited) {
    if (!keepAlive && !ENABLE_KEEP_ALIVE) {
      visited.forEach((el) => {
        keepAliveStore.delCachePage(el)
      })
    }
    keepAliveStore.resetVisited()
  }
}
